<template>
	<!-- <my-nav-bar bgType="WhiteFrostedGlass"></my-nav-bar> -->
	<my-nav-bar bgType="OrangeFrostedGlass" title="预约一下~"></my-nav-bar>
	
	<view class="AppointmentPage pageBg">
		
		<view class="placeholder" :style="{height: getNavBarHeight() + 'px'}"></view>
		
		<view class="WeekdaySelector Module_full">
			<view class="selectIndicator_shadow" :style="{ left: selectIndicatorTransformX +'px' }"></view>
			<view class="ModuleTitle"> 请选择日期 </view>
			<hr class="grey-line">
			<view class="WeekdayWhole Whole">
				<view class="WeekdayUnit selectUnit" v-for="(item,index) in WeekdaysMapping" :key="index" @click="changeSelectedDate(index)" :class="[ (selectedDay==index+1) ? 'selected' : '' ]">
					<!-- {{item.chineseName}} ... {{item.date}} -->
					<view class="WeekdayBox selectBox">
						<view class="chineseName"> {{item.chineseName}} </view>
						<view class="date"> {{item.date}}号 </view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="HHMMTimeSelector Module_full">
			<view class="selectIndicator_shadow" :style="{ left: selectIndicatorTransformX2 +'px' }"></view>
			<view class="ModuleTitle"> 请选择时间 </view>
			<hr class="grey-line">
			<view class="HHMMTimeWhole Whole">
				<view class="HHMMTimeUnit selectUnit" v-for="(item,index) in AppointTimeInOneDay[isWeekend]" :key="index" @click="changeSelectedTime(index)" :class="[ selectedHHMMTimeIdx==index ? 'selected' : '' ]">
					<view class="HHMMTimeBox selectBox">
						<view class="HHMMTimeNumber"> {{item}} </view>
						<view class="occupyStatus"> 可约 </view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="ServiceSelector Module_full">
			<view class="ModuleTitle"> 请选择服装 _[placeholder]_ </view>
			<uni-icons type="right" class="right-arrow" size="30"></uni-icons>
			<hr class="grey-line">
			<view class="bottomBox">
				
			</view>
		</view>
		
		<view class="LocationSelector Module">
			<view class="row">
				<view class="ShopName"> 七彩童年（萍乡店） </view>
			</view>
			<view class="row">
				<view class="AddressName"> 江西省萍乡市安源区楚萍东路200-1 金典城北门3号楼 </view>
				<view class="DistanceDisplay"> {{}}11km </view>
			</view>
		</view>
		
		<view class="confirmInfoArea">
			<view class="content">
				<view class="infoBox">
					<view class="row confirmHint">
						确认您的预约信息
					</view>
					<!-- {{ selectedDateObj }} -->
					<view class="row">
						<view class="key"> 日期 </view>
						<view class="value"> {{ selectedDateObj.getMonth()+1}} 月 {{selectedDateObj.getDate()}} 日， {{ WeekdaysMapping[selectedDay-1].chineseName }} </view>
					</view>
					<view class="row">
						<view class="key"> 时间 </view>
						<view class="value"> {{ AppointTimeInOneDay[isWeekend][selectedHHMMTimeIdx] }} </view>
					</view>
					<view class="row">
						<view class="key"> 地点 </view>
						<view class="value"> 七彩童年-萍乡店 </view>
					</view>
				</view>
				<view class="buttonBox">
					<button class="commitButton" @click="onClickCommitButton"> 确认预约 </button>
				</view>
			</view>
			<view class="stepping-stone">
				<!-- dian -->
			</view>
			
		</view>
	
	</view>
	
	
	<floating-window :class="['float', String(float_class_name)]" :PhaseIdx="FloatingWindowPhaseIdx">
		<view class="infoBox">
			<view class="row confirmHint">
				请再次确认您的预约信息
			</view>
			<!-- {{ selectedDateObj }} -->
			<view class="row">
				<view class="key"> 日期 </view>
				<view class="value"> {{ selectedDateObj.getMonth()+1}} 月 {{selectedDateObj.getDate()}} 日， {{ WeekdaysMapping[selectedDay-1].chineseName }} </view>
			</view>
			<view class="row">
				<view class="key"> 时间 </view>
				<view class="value"> {{ AppointTimeInOneDay[isWeekend][selectedHHMMTimeIdx] }} </view>
			</view>
			<view class="row">
				<view class="key"> 地点 </view>
				<view class="value"> 七彩童年-萍乡店 </view>
			</view>
		</view>
		<view class="buttonBox">
			<button class="cancelButton button" @click="onClickCancel">再想想</button>
			<button class="sendButton button" @click="onClickSend" >确认发送</button>
		</view>

	</floating-window>
	
	<my-nav class="down-nav" :y="Number(3)" :x="XRef"></my-nav>
</template>

<script setup>
	import { ref } from 'vue';
	import { onLoad, onReady, onShow, onHide, onUnload, onPageScroll } from "@dcloudio/uni-app";
	import { SYSTEM_INFO, getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIcon, RpxToPx } from '@/utils/system.js';
	import { getCurrentIdx, toUrl } from "@/utils/page.js";
	import { BASE_URL, request } from "@/utils/request.js";
	import { formatDateToChinese } from "@/utils/string.js";
		
	const selectIndicatorTransformX = ref( 10 + (uni.getWindowInfo().screenWidth-20)/7/2 - 25 );
	const selectIndicatorTransformX2 = ref( 10 + (uni.getWindowInfo().screenWidth-20)/5/2 - 25 );
	
	const app = getApp();
	const UserInfoFromServer = app.globalData.UserInfoFromServer;

	const selectedDay = ref(0);
	const selectedDateObj = ref(new Date());
	const isWeekend = ref(0);
	const selectedHHMMTimeIdx = ref(0);
	
	const weekDaysArray = ref([]);
	const WeekdaysMapping = ref([
		{ chineseName: "周一", date: -1 },
		{ chineseName: "周二", date: -1 },
		{ chineseName: "周三", date: -1 },
		{ chineseName: "周四", date: -1 },
		{ chineseName: "周五", date: -1 },
		{ chineseName: "周六", date: -1 },
		{ chineseName: "周日", date: -1 },
	]);
	const AppointTimeInOneDay = ref([
		["08:00", "10:30", "13:00", "15:00", "17:00"],
		["08:00", "10:30", "13:00", "15:00", "16:30"],
	]);
	
	const float_class_name = ref('');
	
	const changeSelectedDate = (index)=>{
		selectedDay.value = index+1;
		selectedDateObj.value = weekDaysArray.value[selectedDay.value-1];
		isWeekend.value = (selectedDay.value>=1 && selectedDay.value<=5) ? 0 : 1;
		// selectIndicatorTransformX.value = 10 + (uni.getWindowInfo().screenWidth-20)/7/2 - 25 + index*(uni.getWindowInfo().screenWidth-20)/7; //shadow
		selectIndicatorTransformX.value = RpxToPx(25+100*index);  //box
		console.log("ref var selectedDay: 周", selectedDay.value);
		console.log("obj in WeekdaysMapping", WeekdaysMapping[selectedDay-1]);
	}
	const changeSelectedTime = (index)=>{
		selectedHHMMTimeIdx.value = index;
		selectIndicatorTransformX2.value = RpxToPx(25+25+140*index);  //box
		console.log("ref var selectedTimeIdx: ", selectedHHMMTimeIdx.value);
	}
	
	
	function getWeekDaysOfThisWeek(date) {  
		if (isNaN(date.getTime())) {  
			throw new Error('Invalid date string');  
		}  

		// 获取该周的周一日期  
		const dayOfWeek = date.getDay(); // getDay()返回的是0（周日）到6（周六）  
		const dayOfWeekOffset = (dayOfWeek === 0) ? -6 : (1 - dayOfWeek); // 如果dayOfWeek是0（周日），则偏移为-6，否则是1减去dayOfWeek  
		const DateObjX = new Date(date.getTime());  
		DateObjX.setDate(DateObjX.getDate() + dayOfWeekOffset + 7);
		selectedDay.value = (dayOfWeek === 0) ? 7 : (dayOfWeek+1);

		// 创建一个数组来存储周一到周日的日期  
		const weekDays = [];  
		for (let i = 0; i < 7; i++) {  
			weekDays.push(new Date(DateObjX.getTime()));  
			DateObjX.setDate(DateObjX.getDate() + 1); // 递增天数  
		}  
	
		return weekDays;  
	}  
	
	const hintLogin = ()=>{
		console.log("un logged in");
		uni.showModal({
			title: "请先登录",
			content: "预约功能需要先登录",
			showCancel: true,
			cancelText: "暂时不",
			confirmColor: '#3CC51F',
			success: function (res) {
			    if (res.confirm) {
			      console.log('用户点击了确定');
				  toUrl('/pages/my/my');
			    } else if (res.cancel) {
			      console.log('用户点击了取消');
			    }
			},
		})
	}
	
	const hintConfirm = ()=>{
		console.log("----预约信息↓----");
		console.log(weekDaysArray.value[selectedDay.value-1]);
		console.log(AppointTimeInOneDay.value[isWeekend.value][selectedHHMMTimeIdx.value]);
		console.log(UserInfoFromServer.value);
		console.log("----预约信息↑----");
		
		float_class_name.value = 'appear';	
	}
	
	const onClickCancel = ()=>{
		float_class_name.value = '';
	}
	
	const onClickSend = async() => {
		
		// 拼接预约时间
		let appointmentDate = new Date(weekDaysArray.value[selectedDay.value - 1]);
		let appointmentTime = AppointTimeInOneDay.value[isWeekend.value][selectedHHMMTimeIdx.value];
		let [hours, minutes] = appointmentTime.split(':');
		appointmentDate.setHours(hours, minutes, 0, 0);
		
		// 构造JSON对象
		let appointmentDataJson = {
		    appointment_time: appointmentDate.toISOString(),
		    user_open_id: UserInfoFromServer.value.open_id
		};
		
		// 打印出要发送的数据以确认
		console.log("----发送的预约数据Json↓----");
		console.log(appointmentDataJson);
		console.log("----发送的预约数据Json↑----");
		
		// 调用封装好的 request 函数发送请求
		request({
		    url: 'appointment/add',
		    method: 'POST',
		    data: appointmentDataJson,
		    header: { 'Content-Type': 'application/json'}
		})
		.then( post_data=>{
			console.log("post data: "); console.log(post_data);
			float_class_name.value = '';
			uni.showModal({
				title: "预约信息已经提交",
				content: "请记住您的预约时间: " + formatDateToChinese( appointmentDataJson.appointment_time ),
				showCancel: false,
				confirmColor: '#3CC51F',
				success: function (res) {
				    if (res.confirm) {
				      console.log('用户点击了确定');
				    } 
				},
			})
		})
	}
	
	const onClickCommitButton = ()=>{
		console.log("onClickCommitButton()");
		if (getApp().globalData.isLoggedIn.value === false){
			hintLogin();
		} else {
			hintConfirm();
		}
	}
	
	
	onLoad(()=>{
		weekDaysArray.value = getWeekDaysOfThisWeek(new Date());
		console.log("selected day value", selectedDay.value);
		console.log("selected dayOfWeek chineseName: ", WeekdaysMapping.value[selectedDay.value-1].chineseName)
		
		isWeekend.value = (selectedDay.value>=1 && selectedDay.value<=5) ? 0 : 1;
		console.log(weekDaysArray); // 输出该周周一到周日的日期数组
		weekDaysArray.value.forEach( (day, idx)=>{
			WeekdaysMapping.value[idx].date = day.getDate();
		});
		console.log("ref var WeekdaysMapping: "); console.log(WeekdaysMapping);
	});
	
	// ---------------------------------------------
	const XRef = ref( Number(3) );
	
	onLoad((event) => {
		XRef.value = event.LastIdx ? Number(event.LastIdx) : 3;
	});
	
</script>

<style lang="scss" scoped>
	
	.selectIndicator_shadow{
		position: absolute;
		left: 0;
		top: 50px;
		width: 50px;
		height: 50px;
		background-color: rgba(250, 150, 0, 0.4);
		box-shadow: 0px 0 10px 5px rgba(250, 150, 0, 0.4);
		border-radius: 75rpx;
		
		transition: 0.25s;
	}
	
	.selectIndicator_box{
		position: absolute;
		z-index: 224524;
		left: 0;
		top: 10%;
		width: 105rpx;
		height: 85%;
		border: 5rpx solid rgba(250, 150, 0, 0.75);
		border-radius: 10px;
		
		transition: 0.25s;
	}
	
	.AppointmentPage{
		// border: 5px solid black;
		position: fixed; top: 0; width: 100%; height: 100%;
		display: grid;
		place-items: center; /* 水平和垂直居中 */
		grid-auto-rows: min-content; /* 子元素自动行高 */
		
		.placeholder{
			width: 80%;
			// border: 2px solid blue;
			// margin-bottom: 10px;
		}
		
		.Module{
			// border: 1px solid red;
			width: 90%;
			border-radius: 50rpx;
			padding: 10rpx;
			// min-height: 100px;
			background-color: rgba(0,0,0,0.2);
			backdrop-filter: blur(10px);
			box-shadow: 5px 5px 5px 2px rgba(0, 0, 0, 0.2); /* 水平偏移量 垂直偏移量 模糊半径 阴影颜色 */
			margin: 0 0 50rpx 0;
		}
		
		.Module_full{
			width: 100%;
			padding: 5px 25rpx 5px 25rpx;
			min-height: 100px;
			background: rgba(255,255,255,0.55);
			backdrop-filter: blur(5.5px);
			box-shadow: 5px 0px 5px 5px rgba(0, 0, 0, 0.2); /* 水平偏移量 垂直偏移量 模糊半径 阴影颜色 */
			margin: 0 0 50rpx 0;
			display: flex; flex-direction: column; 
			
			.ModuleTitle{
				width: 100%;
				// border: 1px solid blue;
			}
			
			.Whole{
				// border: 1px solid red;
				display: flex; flex-direction: row;
				height: 100%;
			}

			
			.grey-line {
				width: 98%;
			    border: 0.9px solid #ccc; /* 灰色边框，可以根据需求调整粗细 */
			    margin-top: 5px; margin-bottom: 5px;
				left: 0; right: 0; margin-left: auto; margin-right: auto;
			}
		}
		
		.selectUnit{
			overflow: hidden;
			background-color: rgba(0,0,0,0);
			
			display: flex; flex-direction: row; justify-content: center; align-items: center;
			flex: 1;
			
			transition: 0.21s;
			
			.selectBox{
				width: 84%;
				height: 98%;
				// border: 1px solid blue;
				border: 1px solid rgba(111,111,111,0.333);
				// background-color: rgba(100,100,100,0.3);
				border-radius: 10.5px;
				transition: 0.42s;
				display: flex; flex-direction: column; justify-content: center; align-items: center;
			}
		}
		
		.selectUnit.selected{
			.selectBox{
				// box-shadow: 0px 0 10px 5px rgba(250, 150, 0, 0.4);
				// box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); /* 添加背景阴影 */
				// border: 2px solid rgba(250, 150, 0, 0.75);
				// background-color: rgba(255,255,255,0.85);
				// background-color: rgba(250, 150, 0, 0.75);;
				transform: scale(1.05);
				transition: 0.21s;
			}
		}
		
		.WeekdaySelector{
			// border: 2px solid red;
			
			height: 111px;
			
			.WeekdayUnit{
				display: flex; flex-direction: row;
				// border: 1px solid blue;
				// border-radius: 10px;
				width: 10%;
				height: 100%;
				
				.WeekdayBox{
				}
				
				.chineseName{
					font-weight: 1000;
					font-size: 20px;
					margin-bottom: 10px;
				}
				.date{
					font-size: 15px;
				}
			}
			
			.WeekdayUnit.selected{
				.WeekdayBox{
				}
			}
		}
		
		.HHMMTimeSelector{
			// border: 1px solid red;
			height: 120px;
			.HHMMTimeUnit{
				// border: 1px solid blue;
				height: 100%;
				flex: 1;
				.HHMMTimeBox{
					.HHMMTimeNumber{
						font-weight: 1000;
						font-size: 20px;
						margin-bottom: 10px;
					}
				}
			}
		}
		
		.ServiceSelector{
			display: flex; flex-direction: column;
			.right-arrow{
				position: absolute; right: 25rpx;
			}

		}
		
		.LocationSelector{
			padding: 20rpx;
			.row{
				display: flex; flex-direction: row;
			}
			
			//row 1
			.row{
				.ShopName{
					font-weight: 1000;
					font-size: 40rpx;
				}
			}
			
			//row 2
			.row{
				.AddressName{
					// border: 1px solid red;
					padding: 0 20% 0 2%;
					flex: 618;
				}
				.DistanceDisplay{
					text-align: center;
					flex: 382;
				}
			}

		}
	
		.confirmInfoArea{
			// border: 2px solid red;
			position: absolute;
			bottom: 0;
			width: 100%;
			display: flex; flex-direction: column;
			box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.8); /* 水平偏移量 垂直偏移量 模糊半径 阴影颜色 */
			.content{
				display: flex; flex-direction: row;
				height: 25%;
				.infoBox{
					// border: 1px solid blue;
					width: 60%;
					padding: 20rpx;
					.row{
						display: flex; flex-direction: row;
						margin: 20rpx;
					}
					
					.row.confirmHint{
						font-weight: 800;
						font-size: 40rpx;
					}
					
					.row{
						.key{
							margin-left: 20rpx;
							font-weight: 800;
						}
						.value{
							margin-left: 10rpx;
							white-space: nowrap;
						}
						
					}
				}
				.buttonBox{
					// border: 1px solid blue;
					width: 40%;
					display: flex; flex-direction: column;
					justify-content: center; align-items: center;
					.commitButton{
						border-radius: 25px;
						height: 50px;
						width: 80%;
						border: 1px solid green;
						color: green;
					}
				}
			}
			
			.stepping-stone{    
				// border: 2px solid red;
				height: 120rpx;
			}
		}
	}
	
	.float{
		z-index: -1;
		opacity: 0;
		position: fixed; top: 0; left: 0;
		height: 100%; width: 100%;
		transform: translateY(-1000px);
		transform: scale(0.5);
		
		transition: 0.5s ease-in-out;
		
		.infoBox{
			// border: 1px solid blue;
			width: 100%; padding: 20rpx;
			.row{
				display: flex; flex-direction: row;
				margin: 20rpx;
			}
			
			.row.confirmHint{
				font-weight: 800;
				font-size: 40rpx;
			}
			
			.row{
				.key{
					margin-left: 20rpx;
					font-weight: 800;
				}
				.value{
					margin-left: 10rpx;
					white-space: nowrap;
				}
				
			}
		}
			
		.buttonBox{
			width: 100%;
			display: flex; flex-direction: row;
			padding: 8%;
			.button{
				width: 40%;
				border-radius: 20px;
			}
			.cancelButton{
				border: 1px solid gray;
			}
			.sendButton{
				border: 1px solid green;
				color: green;
			}
		}
	}
	
	.float.appear{
		z-index: 2929820;
		opacity: 1;
		transform: translateY(0px);
		transform: scale(1);
		
		transition: 0.5s ease-in-out;
		
		display: flex; flex-direction: column; justify-content: center; align-items: center;
 		
		
	}
	
	.down-nav{
		// border: 10px solid red;
		position: fixed;
		bottom: 20rpx;
	}
</style>
